package com.williams.myo2o.web.shopAdmin;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.williams.myo2o.dto.ShopExecution;
import com.williams.myo2o.entity.Area;
import com.williams.myo2o.entity.PersonInfo;
import com.williams.myo2o.entity.Shop;
import com.williams.myo2o.entity.ShopCategory;
import com.williams.myo2o.enums.ShopStateEnum;
import com.williams.myo2o.service.AreaService;
import com.williams.myo2o.service.ShopCategoryService;
import com.williams.myo2o.service.ShopService;
import com.williams.myo2o.util.HttpServletRequestUtil;
import com.williams.myo2o.util.ImageUtil;
import com.williams.myo2o.util.PathUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @auther williams
 * @create-time 2018-07-29-下午8:45
 */

//实现店铺管理相关的逻辑

@Controller
@RequestMapping("/shopadmin")
public class ShopManagementController {
    @Autowired
    private ShopService shopService;

    @Autowired
    private AreaService areaService;

    @Autowired
    private ShopCategoryService shopCategoryService;


    @RequestMapping(value = "/getshopinitinfo",method = RequestMethod.GET)
    @ResponseBody
    private Map<String,Object> getShopInitInfo(){
        Map<String,Object> modelMap = new HashMap<String, Object>();
        List<ShopCategory> shopCategoryList = new ArrayList<>();
        List<Area> areaList = new ArrayList<>();
        try{
            shopCategoryList = shopCategoryService.getShopCategoryList(new ShopCategory());
            areaList = areaService.getAreaList();
            modelMap.put("shopCatrgoryList",shopCategoryList);
            modelMap.put("areaList",areaList);
            modelMap.put("success",true);

        }catch(Exception e){
            modelMap.put("success",false);
            modelMap.put("errMsg",e.getMessage());
        }
        return modelMap;

    }



    @RequestMapping(value = "/registershop",method = RequestMethod.POST)
    @ResponseBody
    private Map<String,Object> registerShop(HttpServletRequest request) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        // 1. 接受并转化相应的参数(用的是 HttpServletRequestUtil 这个工具类去接收，用 jackson-databind 去转化)，包括店铺信息以及图片信息
        //这个方法的作用是接收前端传过来店铺相关的字符串的信息，然后将它转换成 Shop 实体类
        String shopStr = HttpServletRequestUtil.getString(request, "shopStr");
        ObjectMapper mapper = new ObjectMapper();
        Shop shop = null;
        try {
            shop = mapper.readValue(shopStr, Shop.class);
        } catch (Exception e) {
            modelMap.put("success", false);
            modelMap.put("errMsg", e.getMessage());
            return modelMap;
        }

        //这个方法的作用是获取前端传来的文件流，将其传到 shopImg 里去
        //CommonsMultipartResolver　是一个文件上传解析器，用于解析 request 里面的文件信息，这个变量需要 new 出来
        CommonsMultipartFile shopImg = null;
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if (commonsMultipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg");
        } else {
            modelMap.put("success", false);
            modelMap.put("errMsg", "上传图片不能为空");
            return modelMap;
        }



        // 2. 注册店铺
        if(shop!=null && shopImg!=null){
            PersonInfo owner = new PersonInfo();
            owner.setUserId(1L);
            shop.setOwner(owner);

//            File shopImgFile =new File(PathUtil.getImageBasePath() + ImageUtil.getRandomFileName());
//            try {
//                shopImgFile.createNewFile();
//            }catch (IOException e){
//                modelMap.put("success", false);
//                modelMap.put("errMsg", e.getMessage());
//                return modelMap;
//            }
//            //因为 CommonsMultipartFile 类型有一个 getInputStream() 方法，先使用这个方法才可以在 CommonsMultipartFile 类型和 File 类型之间互转
//            try {
//                inputStreamToFile(shopImg.getInputStream(),shopImgFile );
//            } catch (IOException e) {
//                modelMap.put("success", false);
//                modelMap.put("errMsg", e.getMessage());
//                return modelMap;
//            }

            //填入前台信息
            //因为 addShop 方法需要传入 File 类型的参数,然而现在传入的 shopImg 为 CommonsMultipartFile 类型的，所以需要转化类型

            ShopExecution se = null;
            try {
                se = shopService.addShop(shop,shopImg.getInputStream(),shopImg.getOriginalFilename());
                if(se.getState()== ShopStateEnum.CHECK.getState()){
                    modelMap.put("success", true);
                }else{
                modelMap.put("success", false);
                modelMap.put("errMsg", se.getStateInfo());
                }
            } catch (IOException e) {
                modelMap.put("success", false);
                modelMap.put("errMsg", e.getMessage());
            }
            return modelMap;
        }

        else{
            modelMap.put("success", false);
            modelMap.put("errMsg", "请输入店铺信息");
            return modelMap;
        }

        // 3. 返回结果

    }

//    //因为 addShop 方法需要传入 File 类型的参数,然而现在传入的 shopImg 为 CommonsMultipartFile 类型的，所以需要转化类型
//
//    private static void inputStreamToFile(InputStream inputStream, File file){
//        FileOutputStream outputStream =null;
//        try{
//            outputStream=new FileOutputStream(file);
//            int bytesRead = 0;
//            byte[] buffer = new byte[1024];
//            while((bytesRead = inputStream.read(buffer)) != -1){
//                outputStream.write(buffer,0,bytesRead);
//            }
//        }catch (Exception e){
//            throw new RuntimeException("调用 inputStreamToFile 产生异常" + e.getMessage());
//        }finally{
//            try{
//                if(outputStream != null){
//                    outputStream.close();
//                }
//                if(inputStream != null){
//                    inputStream.close();
//                }
//            }catch (IOException e){
//                throw new RuntimeException("inputStreamToFile 关闭IO产生异常" + e.getMessage());
//            }
//        }
//
//    }


}
